<template>
  <t-dialog
      header="新增链连接"
      :visible.sync="showDialogAdd"
      @confirm="onConfirm"
      width='50%'
    >
    <t-space size="32px">
    <t-form
      :data="formData"
      labelWidth="calc(2em + 50px)"
      labelAlign="right"
      Align="right"
      :rules="formRules"
      :layout="layout"
      ref="form"
      scrollToFirstError="smooth"
    >
      <t-form-item label="链名称" name="chain_name">
        <t-input v-model="formData.chain_name" placeholder="请输入链名称" ></t-input>
      </t-form-item>
      <t-form-item label="链ID" name="chain_id">
        <t-input v-model="formData.chain_id"  placeholder="请输入链id"></t-input>
      </t-form-item>
      <t-form-item label="AuthType" name="auth_type">
        <t-select
          v-model="formData.auth_type"
          :style="{ width: '222px' }"
          class="demo-select-base"
          placeholder="请选择类型"
          clearable
        >
          <t-option v-for="(item, index) in AUTH_TYPE_OPTIONS" :key="index + item.path" :value="item.value" :label="item.label">
            {{ item.label }}
          </t-option>
        </t-select>
      </t-form-item>
      <t-form-item label="Crypto" name="crypto_hash" layout="inline">
        <t-select
          v-model="formData.crypto_hash"
          :style="{ width: '222px' }"
          placeholder="请选择类型"
          class="demo-select-base"
          clearable
        >
          <t-option v-for="(item, index) in CRYPTO_HASH_OPTIONS" :key="index + item.path" :value="item.value" :label="item.label">
            {{ item.label }}
          </t-option>
        </t-select>
      </t-form-item>
      <t-form-item label="Crypto-config" name="files" labelWidth="calc(2em + 100px)">
        <div class="tdesign-demo-upload">
        <div style="width: 500px">
          <t-upload
            :action="uploadApi"
            :tips="tips"
            v-model="files"
            :beforeUpload="beforeUpload"
            @fail="handleFail"
            @success="onSuccess"
            theme="file-input"
            placeholder="未选择文件"
          ></t-upload>
        </div>
        </div>
      </t-form-item>

      <t-form-item v-for="(item, index) in this.formData.node_list" :key="index" label="节点地址" :name="item.node_name">
        <!-- <span>{{ item.id }}</span> -->
        <t-input v-model="item.node_name" placeholder="请输入节点名称" style="margin-right: 10px;"></t-input>
        <t-input v-model="item.node_addr"  placeholder="请输入节点ip:port"></t-input>
        <t-button
          v-if="index === 0 || index === lastAddNodeList - 1"
          @click="addNodeList"
          slot="statusIcon"
          variant="dashed"
        >
          <icon name="add" />
        </t-button>
        <t-button v-if="index > 0" @click="removeNodeList(item, index)" slot="statusIcon" variant="dashed">
          <icon name="remove" />
        </t-button>
      </t-form-item>
      <t-form-item :statusIcon="false" style="margin-left: 80px"></t-form-item>
    </t-form>
  </t-space>
  </t-dialog>
</template>

<script lang="jsx">
import { operateChainConn } from '@/api/requestApi';
import { Icon } from 'tdesign-icons-vue';
import {
  AUTH_TYPE_STATUS,
  AUTH_TYPE_OPTIONS,
  CRYPTO_HASH_STATUS,
  CRYPTO_HASH_OPTIONS,
} from '@/constants';


const INITIAL_FORM_DATA = {
  chain_id: '',
  chain_name: '',
  node_list: [{ node_name: '', node_addr: '', node_path: '' }],
  auth_type: undefined,
  crypto_hash: undefined,
  crypto_config: '',
};
const FORM_RULES = {
  chain_name: [{ required: true, message: '请输入链名称', type: 'error' }],
  auth_type: [{ required: true, message: '请选择认证类型', type: 'error' }],
  crypto_hash: [{ required: true, message: '请选择加密算法', type: 'error' }],
  chain_id: [{ required: true, message: '请输入ChainID', type: 'error' }],
};

export default {
  name: 'AddDialogComp',
  components: {
    Icon,
  },
  props: {
    showChildDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {    
      AUTH_TYPE_STATUS,
      AUTH_TYPE_OPTIONS,
      CRYPTO_HASH_STATUS,
      CRYPTO_HASH_OPTIONS,
      layout: 'vertical', // 行内布局
      files: [], // 文件上传
      tips: '请上传zip或gz包', // 文件上传
      uploadApi: '/api/crypto/upload',
      lastAddNodeList: 1,
      crypto_config: '',
      formData: {...INITIAL_FORM_DATA},
      formRules: {...FORM_RULES},
    };
  },
  
  computed: {
    showDialogAdd: {
      get() {
        return this.showChildDialog
      },
      set(newValue) {
        this.$emit('update:showChildDialog', newValue) // 触发更新事件，父组件的showDialogAdd会自动更新
      }
    }
  },
  mounted() {
    this.formData.node_list = [{ node_name: '', node_addr: '', node_path: '' }];
    // this.$refs.formValidatorStatus.validate();
  },
  methods: {
    // init(data) {
    //   // this.showDialogAdd=true;
    //   // data是父组件弹窗传递过来的值，我们可以打印看看
    //   this.formData = data;
    //   console.log('来自父组件的', data);
    // },

    onConfirm() {
      console.log('formData--->',this.formData)
      const reqParam = {"ids": [''], "param": {}, "op_type": ''};
      this.formData.crypto_config = this.crypto_config;
      reqParam.param = this.formData;
      reqParam.op_type = 1;
      // console.log("提交的表单内容", reqParam);
      operateChainConn(reqParam)
        .then((res) => {
          if (res.data.code === '000') {
            this.$message.success('链连接创建成功');
          }
        })
        .catch((e) => {
          this.$message.error('系统异常');
          console.log(e);
        })
        .finally(() => {
          this.dataLoading = false;
        });
      this.formData.node_list = [{ node_name: '', node_addr: '', node_path: '' }];
      this.showDialogAdd = false;
      // 刷新父页面
      this.$emit('addFlush')
    },
    // onConfirmAnother(context) {
    //   console.log('111点击了确认按钮', context);
    //   this.$emit('addFlush')
    // },
    // close(context) {
    //   // this.$emit('addOrUpdateVisible', false)
    //   console.log('关闭弹窗，点击关闭按钮、按下ESC、点击蒙层等触发', context);
    // },
    // onCancel(context) {
    //   // this.showDialogAdd = false;
    //   console.log('点击了取消按钮', context);
    // },
    // onKeydownEsc(context) {
    //   console.log('按下了ESC', context);
    // },
    // onClickCloseBtn(context) {
    //   console.log('点击了关闭按钮', context);
    // },
    // onClickOverlay(context) {
    //   console.log('点击了蒙层', context);
    // },
    // 文件上传-失败
    handleFail({ file }) {
      this.$message.error(`文件 ${file.name} 上传失败`);
    },
    // 文件上传-成功
    onSuccess({file}) {
      // console.log(file,file.response.data.files_path);
      file.name = file.response.data.files_path;
      this.crypto_config = file.name;
    },
    beforeUpload(file) {
      if ((!/(\.(zip)|\.(gz))$/.test(file.name))) {
        this.$message.warning('请上传zip或tar.gz压缩包');
        return false;
      }
      return true;
    },
    // 用于格式化接口响应值，error 会被用于上传失败的提示文字；url 表示文件/图片地址
    formatResponse(res) {
      return { ...res, error: '上传失败，请重试', url: res.url };
    },

    addNodeList() {
      this.formData.node_list.push({ node_name: '', node_ipaddr: '' });
      this.nodeListNum += 1;
    },
    removeNodeList(item, index) {
      delete INITIAL_FORM_DATA[`add${item.id}`];
      this.formData.node_list.splice(index, 1);
    },
  },
  
};
</script>

<style lang="less" scoped>

</style>
